package cn.islu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession(false);

        String uri = request.getRequestURI();
        if (uri.endsWith("/login.jsp") || uri.endsWith("/Login")) {
            filterChain.doFilter(request, response);
        } else if (uri.endsWith("/register.jsp") || uri.endsWith("/Register")) {
            filterChain.doFilter(request, response);
        } else if (session != null) {
            filterChain.doFilter(request, response);
        } else if (request.getAttribute("username") != null) {
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect("/jsp/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
